import {
	BitSet,
	BitClr,
	Set2Byte,
	DataGet,
	ab2hex,
	hexCharCodeToStr,
	arrayToBuffer,
	Parse,
	Set3Byte,
	bitToStr,
	Set1Byte,
	feedback,
	Set4Byte,
	Get2Byte,
	Get4Byte,
	Get3Byte,
	getByBite,
	uploadEquipCommlog,
} from "@/utils/index.js";
import {
	serviceId,
	characteristicId2,
} from "@/utils/service.js";
import {
	equipCommlog
} from "@/api/api.js";
import {
	READ_AND_WRITE_STATUS,
} from "@/common/config.js";
export default {
	data() {
		return {
			startTime: null, //开始时间戳
		}
	},
	methods: {
		isRead() {
			let that = this;
			uni.showModal({
				title: '提示',
				content: '确定要一键诊断吗？',
				success(res) {
					if (res.confirm) {
						that.isProcess = true;
						that.currentCollapse = 0;
						that.command = 8;

						that.doRead();
					}
				}
			})
		},
		// 数据重置
		resetData() {
			this.isCanvasShow = false;
			this.isDiagnosis = true;
			this.statusResult = '';
			this.isShow = 0;
			this.percent = 0;
			this.GRADE = 100;
			for (let key of Object.keys(this.masterControl)) {
				this.masterControl[key] = "";
			}
		},
		// 一键诊断 读取设备信息
		async doRead(addr) {
			let that = this;
			that.resetData();
			this.startTime = new Date().getTime();

			let datas = DataGet(this.command, 0, addr ? addr : 0, 0, 0, null);
			let buffer = arrayToBuffer(datas);
			let requestHex = ab2hex(buffer);
			
			let {
				deviceId,
			} = this.deviceInfo;
			uni.writeBLECharacteristicValue({
				deviceId,
				serviceId,
				characteristicId: characteristicId2,
				// 这里的value是ArrayBuffer类型
				value: buffer,
				success(res) {
					setTimeout(()=>{
						that.doCharData(addr);
					},300)
					uploadEquipCommlog(requestHex, '', READ_AND_WRITE_STATUS[1], 1, that.startTime,
						that.deviceInfo,'一键诊断成功');
				},
				fail(err) {
					console.log(err)
					that.$Toast.none(`${that.dgMessage}检测失败!`);
					that.statusResult = '2';
					that.isProcess = false;
					uploadEquipCommlog(requestHex, '', READ_AND_WRITE_STATUS[1], 0,that.startTime,
						that.deviceInfo,'一键诊断：'+err.errMsg);
				}
			})
		},
		// 读取数据
		doCharData(addr) {
			let {
				deviceId
			} = this.deviceInfo;
			let that = this;

			this.startTime = new Date().getTime();
			
			// 读取低功耗蓝牙设备的特征值的二进制数据值
			uni.readBLECharacteristicValue({
				deviceId,
				serviceId,
				characteristicId: characteristicId2,
				success(res) {
					uni.onBLECharacteristicValueChange(function(res) {
						// that.isProcess = false;

						// 解析数据
						// let value = res.value ? ab2hex(res.value) : '';
						let buffer = res.value;
						const uint8Array = new Uint8Array(res.value);
						const newArray = Array.from(uint8Array);
						let databuff = Parse(newArray);

						uploadEquipCommlog('', ab2hex(res.value), READ_AND_WRITE_STATUS[0], 1,that.startTime,
						that.deviceInfo,'一键诊断成功');
						
						if (databuff.databuff && databuff.databuff.length == 9) {
							let arr1 = getByBite(databuff.databuff[0]);
							for (let i = 0; i < 3; i++) {
								that.masterControl[`param${i+1}`] = String(arr1[i]);
							}

							for (let i = 1; i < 9; i++) {
								that.masterControl[`param${i+3}`] = String(databuff.databuff[i]);
							}

							that.isCanvasShow = true;

							// 进度条
							that.startProgress();
							that.startShow();
							that.computeGrade();
						}
					})
				},
				fail(fal) {
					console.log("读取数据数据失败", fal)
					that.$Toast.none(`${that.dgMessage}检测失败!`);
					that.statusResult = '2';
					that.isShow = 0;
					that.isProcess = false;
					
					uploadEquipCommlog('', fal.errCode, READ_AND_WRITE_STATUS[0], 0,that.startTime,
						that.deviceInfo,'一键诊断：'+fal.errMsg);
				}
			})
		},
		startShow() {
			const timer = setInterval(() => {
				this.isShow += 1;
				if (this.isShow >= 4) {
					clearInterval(timer);
				}
			}, 1250);
		},
		startProgress() {
			const timer = setInterval(() => {
				this.percent += 1;
				if (this.percent >= 100) {
					this.isProcess = false;
					clearInterval(timer);
				}
			}, 50);
		},
		// 计算分值
		computeGrade() {
			// 摄像头 10分；4G是否在线 10分；
			// 信号质量 7分
			// 软件 14
			// 硬件:仓控版5；充电电源（输出继电器）5；电子锁5；格口温度4；电表状态4
			// 综合:柜体温度5;本地仓禁个数10;设备利用率6
			let param1 = 0;
			if (this.masterControl.param1 == 1) {
				param1 = 10;
			}
			if (this.masterControl.param2 == 1) {
				param1 += 10;
			}

			let param4 = 7 - Math.floor(this.masterControl.param4 / 100 * 7);

			let param5 = 5 - Math.floor(this.masterControl.param5 / 100 * 5);
			let param6 = 5 - Math.floor(this.masterControl.param6 / 100 * 5);
			let param7 = 5 - Math.floor(this.masterControl.param7 / 100 * 5);
			let param3 = this.masterControl.param3 == 1 ? 4 : 0;
			let param8 = 4 - Math.floor(this.masterControl.param8 / 100 * 4);

			let param33 = param3 + param5 + param6 + param7 + param8;

			let param9 = 5 - Math.floor(this.masterControl.param9 / 100 * 5);
			let param10 = 10 - Math.floor(this.masterControl.param10 / 100 * 10);
			let param11 = 6 - Math.floor(this.masterControl.param11 / 100 * 6);
			let param44 = param9 + param10 + param11;

			let arrData = [param1, param4, param33, param44];
			let index = 0;

			const timer = setInterval(() => {
				if (index < arrData.length) {
					if (+this.GRADE > +arrData[index]) {
						this.GRADE -= arrData[index];
					}
					index++;
				} else {
					clearInterval(timer); // 当所有值都输出完毕后清除定时器
				}
			}, 1250);
		},
		
	},
}